package com.example.keshe0337.ui;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.keshe0337.R;
import com.example.keshe0337.biz.UserService;
import com.example.keshe0337.entity.User;

public class RegisterActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        UserService userService = new UserService(this);

        EditText etName = findViewById(R.id.et_name);
        EditText etPhone = findViewById(R.id.et_phone);
        EditText etPassword = findViewById(R.id.et_password);
        EditText etPassword0 = findViewById(R.id.et_password0);
        Button btn = findViewById(R.id.btn_register);

        btn.setOnClickListener(v -> {
            String name = etName.getText().toString();
            String phone = etPhone.getText().toString();
            String password = etPassword.getText().toString();
            String password0 = etPassword0.getText().toString();
            if (name.isBlank() || phone.isBlank() || password0.isBlank() || password.isBlank()) {
                Toast.makeText(this,"请检查信息完整性", Toast.LENGTH_SHORT).show();
                return;
            }

            if (!password0.equals(password)) {
                Toast.makeText(this,"两次输入密码不同", Toast.LENGTH_SHORT).show();
                return;
            }
            User user = new User();
            user.setPhone(phone);
            user.setName(name);
            user.setPassword(password);
            int register = userService.register(user);
            if (register == 0) {
                Toast.makeText(this,"注册成功", Toast.LENGTH_SHORT).show();
                new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(() -> {
                    Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                    startActivity(intent);
                    finish(); // 关闭当前 Activity
                }, 1000); // 延时 2 秒（2000 毫秒）
            }
            if (register == 1) {
                Toast.makeText(this,"该号码重复注册", Toast.LENGTH_SHORT).show();
            }
            if (register == 2) {
                Toast.makeText(this,"手机号码格式有误", Toast.LENGTH_SHORT).show();
            }
            if (register == 3) {
                Toast.makeText(this,"密码设置过短", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
